package com.youshang.designpattern;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

public class OpenAIApiExample {
    public static void main(String[] args) {
        // 设置 OpenAI API 的访问密钥
        String apiKey = "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";

        // 设置 API 请求的 URL
        String apiUrl = "https://api.openai.com/v1/engines/davinci-codex/completions";

        // 设置请求的 JSON 数据
        String requestData = "{\"prompt\": \"Hello, world!\", \"max_tokens\": 10}";

        // 创建 HTTP 客户端
        CloseableHttpClient httpClient = HttpClients.createDefault();

        // 创建 HTTP POST 请求
        HttpPost httpPost = new HttpPost(apiUrl);

        // 设置请求头
        httpPost.setHeader(HttpHeaders.AUTHORIZATION, "Bearer " + apiKey);
        httpPost.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");

        try {
            // 设置请求体数据
            httpPost.setEntity(new StringEntity(requestData));

            // 发送请求并获取响应
            HttpResponse response = httpClient.execute(httpPost);

            // 解析响应
            HttpEntity responseEntity = response.getEntity();
            String responseBody = EntityUtils.toString(responseEntity);

            // 输出响应结果
            System.out.println(responseBody);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭 HTTP 客户端
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
